import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef } from 'react';
import { getAllArea, IArea, saveArea, updateArea } from 'api/Area';
import { useRequest, useHover } from 'ahooks';
import { FormOutlined, EnvironmentOutlined, CheckOutlined, CloseOutlined, PlusSquareOutlined } from '@ant-design/icons';
import './index.less';
import { Input, message, Card } from 'antd';
interface AreaItemProps {
    area: IArea;
    areas: IArea[];
    setAreas: (value: IArea[]) => void;
    inEditArea: string;
    setInEditArea: (value: string) => void;
    updateAreas: Function;
    selectedArea: number;
    setSelectedArea: (value: any) => void;
}
const AreaItem = (props: AreaItemProps) => {
    const hoverRef: any = useRef();
    const isHover = useHover(hoverRef);
    const [newAreaName, setNewAreaName] = useState('');
    /** 编辑区域 */
    const editArea = () => {
        props.setAreas(props.areas.filter((item) => item.id !== undefined));
        props.setInEditArea(props.area.name);
        setNewAreaName(props.area.name);
    };
    /** 保存编辑或保存新增 */
    const createOrUpdateArea = () => {
        if (!newAreaName) {
            message.warning('区域名不能为空');
            return;
        }
        const { id, name } = props.area;
        if (id) {
            if (newAreaName === name) return;
            updateArea({ id, name: newAreaName }).then(() => {
                message.success('更新区域名成功');
                props.setInEditArea('');
                props.updateAreas();
            });
        } else {
            saveArea({ name: newAreaName }).then(() => {
                message.success('新增区域成功');
                props.updateAreas();
            });
        }
    };
    /** 取消编辑或新增 */
    const cancelEdit = () => {
        props.setAreas(props.areas.filter((item) => item.id !== undefined));
        props.setInEditArea('');
    };
    return (
        <div
            className={`area-item flex-align ${props.selectedArea === props.area.id && 'selected-area'}`}
            ref={hoverRef}
            onClick={() => props.setSelectedArea(props.area.id)}
        >
            <EnvironmentOutlined className="mr10" />
            {props.inEditArea === props.area.name ? (
                <>
                    <Input
                        className="area-name"
                        defaultValue={newAreaName}
                        onChange={(e) => setNewAreaName(e.target.value.trim())}
                    />
                    <CheckOutlined className="ml10 pointer" onClick={() => createOrUpdateArea()} />
                    <CloseOutlined className="ml10 pointer" onClick={() => cancelEdit()} />
                </>
            ) : (
                <>
                    <div className="area-name">{props.area.name}</div>
                    {isHover && <FormOutlined className="ml10" onClick={editArea} />}
                </>
            )}
        </div>
    );
};

interface AreaProps {
    selectedArea: number;
    setSelectedArea: (value: number) => void;
}
/** 区域展示 */
const Area = ({ selectedArea, setSelectedArea }: AreaProps, ref: any) => {
    const [areas, setAreas] = useState<IArea[]>([]);
    let { run } = useRequest(getAllArea, {
        manual: true,
        onSuccess: (result) => {
            setAreas(result);
            if (result[0] && result[0].id) {
                setSelectedArea(result[0].id);
            }
        },
    });
    useEffect(() => {
        run();
    }, []);
    useImperativeHandle(ref, () => {
        return {
            areas
        }
    })
    const [inEditArea, setInEditArea] = useState('');
    /** 新建区域 */
    const createArea = () => {
        if (areas.find((item) => item.id === undefined)) return;
        setAreas([...areas, { name: '' }]);
        setInEditArea('');
    };
    const areaProps = {
        areas,
        setAreas,
        inEditArea,
        setInEditArea,
        updateAreas: run,
        selectedArea,
        setSelectedArea,
    };
    return (
        <Card className="area-view">
            <div>区域总览</div>
            <div className="area-list">
                {areas ? (
                    areas.map((item: IArea) => <AreaItem key={item.name} area={item} {...areaProps}></AreaItem>)
                ) : (
                    <div>暂无区域</div>
                )}
            </div>
            <PlusSquareOutlined className="pointer ml10" onClick={createArea} />
        </Card>
    );
};
export default forwardRef(Area);
